package com.exam.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.exam.dao.GradeDao;
import com.exam.dao.PaperDao;
import com.exam.dao.QuestionDao;
import com.exam.dao.StudentDao;
import com.exam.model.PaperModel;
import com.exam.model.QuestionForm;
import com.exam.service.PageService;
import com.exam.util.Tools;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class PaperAction implements RequestAware,SessionAware,ModelDriven<PaperModel>,Preparable{
	
	private String message;
	private PaperModel testPaper;
	
	private String id;  //试卷id
	
	private String pageNow;
	
	//筛选条件
	private String key="";
	private int status=-1;
	
	
	private Map<String, Object> application; 


	/**
	 * 后台 试卷列表
	 * @return
	 */
	public String list(){
		PaperDao pdao = new PaperDao();
		key = Tools.getUTF8Str(key);
		try {
			PageService page = new PageService(pdao.getCount(key, status), "paper-list.action?key="+key+"&status="+status+"&", pageNow);
			this.request.put("PaperList", pdao.getPaperList(key, status, page.getLimit()));
			this.request.put("pageInfo", page.getPageInfo());
			this.request.put("pageList", page.getPageList());
		} catch (SQLException e) {
		
			e.printStackTrace();
		}
		return "list";
		
	}
	
	
	/**
	 * 管理员删除试卷
	 * @return
	 */
	public String delete(){
		new PaperDao().deletePaper(id);
		return "delete";
	}
	
	/**
	 * 管理员结束考试
	 * @return
	 */
	public String testFinished(){
		new PaperDao().testFinished(id);
		return "finished";
	}
	
	/**
	 * 获取试卷
	 * @return
	 */
	public String getPaper(){
		System.out.println("getPaper...");	
		try {
			/**
			 * 1.检测是否恶意登陆
			 * 2.检测试卷是否发布
			 * 3.获取学生信息
			 * 3.获取试卷信息
			 * 4.获取试题
			 */
			//1。
			if(session.get("student")!=null){
				PaperDao pd = new PaperDao();
				StudentDao sd = new StudentDao();
				QuestionDao qd = new QuestionDao();
				GradeDao gd = new GradeDao();
				String sid = (String)session.get("student");
				PaperModel pm ;
				if(pd.hasTestPaper()){  //判断试卷是否
					pm = pd.getTestPaper(); System.out.println(pm.toString());
					if(!gd.isExistGrade(sid, pm.getId())){  //判断是否已考
					//计算剩余考试时间
					pm.setLastTestTime((int) Tools.getTestTime(pm.getCtime(),pm.getTestTime()));
					ArrayList<QuestionForm> list = qd.getOneQuestionForPaper(pm.getQuestionNum(), pm.getDbid() , pm.getType());
					//加密答案字串
					String realAnswer = "EXAM";
					for(int i=0 ;i<list.size() ;i++){
						realAnswer += list.get(i).getAnswer();
					}
					pm.setRealAnswer(Tools.encodeBase64(realAnswer));
					System.out.println("答案："+Tools.encodeBase64(realAnswer));
					System.out.println(Tools.decodeBase64(Tools.encodeBase64(realAnswer)));
					//获取考生信息
					this.request.put("student", sd.getOneStudent(sid));
					
					//试卷信息
					this.request.put("paperInfo", pm);
					//获取试题
					this.request.put("Question", list);
						return "success";
					}else{
						message = "你已经考试完毕!请不要重复考试！";
						this.cutCountStudent();
						return "create-error";
					}
			  }else{
				  message = "没有创建试卷!请先创建试卷!";
				  this.cutCountStudent();
				  return "create-error";
			  }
				
			}else{
				message = "非法登陆！";
				return "create-error";
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * 创建试卷
	 */
	public String create(){
		PaperDao pd = new PaperDao();
		try {
			if(!pd.hasTestPaper()){
				if(pd.createPaper(testPaper)){
					System.out.println(testPaper.toString());
					//初始化 创建在线人数统计
					ActionContext.getContext().getApplication().put("countStudent", 0);
					message = "ok";
					
				}else{
					message = "error";
				}
			}else{
				message = "检测到已有正在考试的试卷,请先结束正在考试的试卷!";
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "create";
	}
	
	public void prepareCreate(){
		testPaper = new PaperModel();
	}
	
	private void cutCountStudent(){
		//在线 人数减少
		application = ActionContext.getContext().getApplication();
		if(application!=null){
			int m = (Integer) application.get("countStudent")-1;
			if(m<0) m=0;
			application.put("countStudent", m);
		}else{
			application.put("countStudent", 0);
		}
		
	}

	Map<String, Object> request;
	public void setRequest(Map<String, Object> req) {
		this.request = req;
	}
	
	Map<String, Object> session;
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	@Override
	public void prepare() throws Exception {
		//不执行这个方法
	}
	@Override
	public PaperModel getModel() {
		return testPaper;
	}
	
	public PaperModel getTestPaper() {
		return testPaper;
	}
	public void setTestPaper(PaperModel testPaper) {
		this.testPaper = testPaper;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPageNow() {
		return pageNow;
	}
	public void setPageNow(String pageNow) {
		this.pageNow = pageNow;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
}
